package cn.gdcp;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private ImageView imageView;
    private Button btnNext;
    private int arr[]={R.drawable.a01,R.drawable.a02,R.drawable.a03,R.drawable.a04,R.drawable.a05} ;
    private int temp;
    private int index = 0;
    private Handler handler;
    private final  int CHANGE_ANDROID = 1001;
    private boolean isPause = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text1);
        textView.setText("I Love Android");
        textView.setTextColor(Color.BLUE);

        imageView = findViewById(R.id.image);
        btnNext = findViewById(R.id.btnNext);

       handler = new Handler(new Handler.Callback() {
           @Override
           public boolean handleMessage(Message msg) {
               if (msg.what == CHANGE_ANDROID){
                   index = (index + 1) % arr.length;
                   imageView.setImageResource(arr[index]);
                   return true;
               }
               return false;
           }
       });

       new Thread(new Runnable() {
           @Override
           public void run() {
               while(true){
                   try{
                       Thread.sleep(2000);
                   }catch (InterruptedException e){
                       e.printStackTrace();
                   }
                   if (!isPause){
                       Message message = new Message();
                       message.what = CHANGE_ANDROID;
                       handler.sendMessage(message);
                   }
               }
           }
       }).start();

       btnNext.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
                   isPause =!isPause;
               }

       });
    }
}
